using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using TerritoryGame.Application.Interfaces;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using System.IO;
using TerritoryGame.Infrastructure.Data;
using TerritoryGame.Domain.Entities.App;
using Microsoft.EntityFrameworkCore;

namespace TerritoryGame.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class SystemController : ControllerBase
{
    private readonly ILogger<SystemController> _logger;

    private readonly TerritoryGameDbContext _dbContext;
    private readonly IAppSystemService _systemService;

    public SystemController(ILogger<SystemController> logger, TerritoryGameDbContext dbContext, IAppSystemService systemService)
    {
        _logger = logger;
        _dbContext = dbContext;
        _systemService = systemService;
    }

    /// <summary>
    /// 系统健康检查
    /// </summary>
    [HttpGet("health")]
    [AllowAnonymous]
    public async Task<IActionResult> HealthCheck()
    {
        try
        {
            // 检查数据库连接
            var dbConnectionOk = await _dbContext.Database.CanConnectAsync();
            


            var healthInfo = new
            {
                // 前端期望的字段名和值
                systemHealth = dbConnectionOk ? "normal" : "abnormal",
                databaseStatus = dbConnectionOk ? "connected" : "disconnected",
                
                // 原有字段
                Status = dbConnectionOk ? "Healthy" : "Unhealthy",
                Timestamp = DateTime.UtcNow,
                Version = "1.0.0",
                Environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development",
                MachineName = Environment.MachineName,
                ProcessId = Environment.ProcessId,
                WorkingSet = GC.GetTotalMemory(false),
                SupportedFileTypes = new string[] { "txt", "pdf", "doc", "docx" }
            };

            _logger.LogInformation("系统健康检查通过");
            return Ok(new { code = 200, message = "系统运行正常", data = healthInfo });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "系统健康检查失败");
            return StatusCode(500, new { code = 500, message = "系统健康检查失败", data = new { error = ex.Message } });
        }
    }

    /// <summary>
    /// 获取系统信息
    /// </summary>
    [HttpGet("info")]
    [AllowAnonymous]
    public IActionResult GetSystemInfo()
    {
        try
        {
            var systemInfo = new
            {
                OS = Environment.OSVersion.ToString(),
                Framework = Environment.Version.ToString(),
                ProcessorCount = Environment.ProcessorCount,
                Is64BitProcess = Environment.Is64BitProcess,
                Is64BitOperatingSystem = Environment.Is64BitOperatingSystem,
                SystemPageSize = Environment.SystemPageSize,
                WorkingSet = Environment.WorkingSet,
                TotalPhysicalMemory = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes,
                ProcessStartTime = Process.GetCurrentProcess().StartTime,
                Uptime = DateTime.UtcNow - Process.GetCurrentProcess().StartTime.ToUniversalTime()
            };

            return Ok(new { code = 200, message = "获取系统信息成功", data = systemInfo });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取系统信息失败");
            return StatusCode(500, new { code = 500, message = "获取系统信息失败", data = new { error = ex.Message } });
        }
    }

    /// <summary>
    /// 获取支持的文件类型
    /// </summary>
    [HttpGet("supported-file-types")]
    [AllowAnonymous]
    public IActionResult GetSupportedFileTypes()
    {
        try
        {
            var supportedTypes = new string[] { "jpg", "jpeg", "png", "gif" };
            return Ok(new { code = 200, message = "获取支持的文件类型成功", data = supportedTypes });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取支持的文件类型失败");
            return StatusCode(500, new { code = 500, message = "获取支持的文件类型失败", data = new { error = ex.Message } });
        }
    }



    /// <summary>
    /// 获取系统统计信息
    /// </summary>
    [HttpGet("statistics")]
    [AllowAnonymous]
    public async Task<IActionResult> GetSystemStatistics()
    {
        try
        {
            var result = await _systemService.GetSystemStatisticsAsync();
            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取系统统计信息失败");
            return StatusCode(500, new { code = 500, message = "获取系统统计信息失败", data = new { error = ex.Message } });
        }
    }

    /// <summary>
    /// 获取系统分析报告
    /// </summary>
    [HttpGet("analytics")]
    [AllowAnonymous]
    public async Task<IActionResult> GetSystemAnalytics()
    {
        try
        {
            var result = await _systemService.GetSystemAnalyticsAsync();
            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取系统分析报告失败");
            return StatusCode(500, new { code = 500, message = "获取系统分析报告失败", data = new { error = ex.Message } });
        }
    }
















}


